<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑广告 - 广告管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .preview-image {
            max-width: 200px;
            max-height: 150px;
            object-fit: cover;
            margin-top: 10px;
        }
        .upload-area {
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            transition: border-color 0.3s;
        }
        .upload-area:hover {
            border-color: #0d6efd;
        }
        .upload-area.dragover {
            border-color: #0d6efd;
            background-color: #f8f9fa;
        }
        .current-image {
            max-width: 150px;
            max-height: 100px;
            object-fit: cover;
            border: 1px solid #dee2e6;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title mb-0">编辑广告</h4>
                    </div>
                    <div class="card-body">
                        <div th:if="${error}" class="alert alert-danger alert-dismissible fade show" role="alert">
                            <span th:text="${error}"></span>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        
                        <form th:action="@{/web/ads/edit/{id}(id=${ad.id})}" method="post" enctype="multipart/form-data">
                            <input type="hidden" name="id" th:value="${ad.id}">
                            <!-- 隐藏字段用于存储上传后的图片URL，默认为当前图片URL -->
                            <input type="hidden" id="imageUrl" name="imageUrl" th:value="${ad.imageUrl}">
                            
                            <div class="mb-3">
                                <label for="name" class="form-label">广告名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="name" name="name" required 
                                       placeholder="请输入广告名称" th:value="${ad.name}">
                            </div>

                            <div class="mb-3">
                                <label for="categoryId" class="form-label">广告分类 <span class="text-danger">*</span></label>
                                <select class="form-select" id="categoryId" name="categoryId" required>
                                    <option value="">请选择分类</option>
                                    <option th:each="category : ${categories}" 
                                            th:value="${category.id}" 
                                            th:text="${category.type}"
                                            th:selected="${ad.categoryId == category.id}"></option>
                                </select>
                            </div>

                            <div class="mb-3" th:if="${ad.imageUrl}">
                                <label class="form-label">当前图片</label>
                                <div>
                                    <img th:src="${ad.imageUrl}" class="current-image" alt="当前广告图片">
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">上传新图片文件</label>
                                <div class="upload-area" id="uploadArea">
                                    <input type="file" class="form-control" id="imageFile" name="imageFile" 
                                           accept="image/*" style="display: none;">
                                    <div id="uploadText">
                                        <i class="bi bi-cloud-upload fs-1 text-muted"></i>
                                        <p class="mb-0">点击选择文件或拖拽文件到此处</p>
                                        <small class="text-muted">支持 JPG, PNG, GIF 格式，最大 5MB</small>
                                    </div>
                                    <div id="uploadProgress" style="display: none;">
                                        <div class="progress">
                                            <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                                        </div>
                                        <small class="text-muted">上传中...</small>
                                    </div>
                                </div>
                                <img id="previewImage" class="preview-image" style="display: none;" alt="预览图片">
                            </div>

                            <div class="d-flex justify-content-between">
                                <a href="/web/ads" class="btn btn-secondary">返回列表</a>
                                <div>
                                    <button type="button" class="btn btn-danger me-2" 
                                            th:onclick="'deleteAd(' + ${ad.id} + ')'">删除广告</button>
                                    <button type="submit" class="btn btn-primary">保存修改</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const uploadArea = document.getElementById('uploadArea');
        const imageFile = document.getElementById('imageFile');
        const previewImage = document.getElementById('previewImage');
        const uploadText = document.getElementById('uploadText');
        const uploadProgress = document.getElementById('uploadProgress');

        // 点击上传区域选择文件
        uploadArea.addEventListener('click', () => {
            imageFile.click();
        });

        // 文件选择处理
        imageFile.addEventListener('change', handleFileSelect);

        // 拖拽处理
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                imageFile.files = files;
                handleFileSelect();
            }
        });

        function handleFileSelect() {
            const file = imageFile.files[0];
            if (file) {
                // 显示预览
                const reader = new FileReader();
                reader.onload = (e) => {
                    previewImage.src = e.target.result;
                    previewImage.style.display = 'block';
                };
                reader.readAsDataURL(file);

                // 上传文件
                uploadFile(file);
            }
        }

        function uploadFile(file) {
            const formData = new FormData();
            formData.append('file', file);

            uploadText.style.display = 'none';
            uploadProgress.style.display = 'block';

            fetch('/api/files/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                uploadProgress.style.display = 'none';
                uploadText.style.display = 'block';
                
                if (data.success) {
                    // 设置图片URL到隐藏字段
                    document.getElementById('imageUrl').value = data.url;
                    showNotification('文件上传成功！', 'success');
                } else {
                    showNotification('文件上传失败：' + (data.message || '未知错误'), 'danger');
                }
            })
            .catch(error => {
                uploadProgress.style.display = 'none';
                uploadText.style.display = 'block';
                console.error('Error:', error);
                showNotification('文件上传失败', 'danger');
            });
        }

        // 自动消除通知功能
        document.addEventListener('DOMContentLoaded', function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                setTimeout(function() {
                    if (alert && alert.classList.contains('show')) {
                        const bsAlert = new bootstrap.Alert(alert);
                        bsAlert.close();
                    }
                }, 5000); // 5秒后自动消除
            });
        });

        // 显示通知函数
        function showNotification(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
            alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            alertDiv.innerHTML = `
                <span>${message}</span>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;
            document.body.appendChild(alertDiv);
            
            // 5秒后自动消除
            setTimeout(function() {
                if (alertDiv && alertDiv.classList.contains('show')) {
                    const bsAlert = new bootstrap.Alert(alertDiv);
                    bsAlert.close();
                }
            }, 5000);
        }

        function deleteAd(id) {
            // 创建删除确认模态框
            const modalHtml = 
                <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                确定要删除这个广告吗？删除后无法恢复！
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-danger" id="confirmDelete">确认删除</button>
                            </div>
                        </div>
                    </div>
                </div>
            
            
            document.body.insertAdjacentHTML('beforeend', modalHtml);
            const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
            modal.show();
            
            // 确认删除按钮事件
            document.getElementById('confirmDelete').addEventListener('click', function() {
                modal.hide();
                fetch('/web/ads/delete/' + id, {
                    method: 'POST'
                })
                .then(response => {
                    if (response.ok) {
                        showNotification('删除成功！', 'success');
                        setTimeout(() => {
                            window.location.href = '/web/ads';
                        }, 1000);
                    } else {
                        showNotification('删除失败', 'danger');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showNotification('删除失败', 'danger');
                });
            });
            
            // 模态框隐藏后清理
            document.getElementById('deleteModal').addEventListener('hidden.bs.modal', function() {
                this.remove();
            });
        }
    </script>
</body>
</html>